<template>
  <div>
    <div class="test"></div>
    <div class="box"></div>
  </div>
</template>

<script>
export default {
  name: 'scroll2IntersectionObserver',
  data() {
    return {};
  },
  methods: {
    /**
     * https://www.vue-js.com/topic/601cc6444590fe0031e59658
     * 工作中经常通过判断元素是否进入视口，一般有三种方式进行判断
     * 1. el.offsetTop - document.documentElement.scrollTop <= viewPortHeight
     * 2. el.getBoundingClientRect().top <= viewPortHeight
     * 3. intersectionRatio > 0 && intersectionRatio <= 1
     * 获取srollTop的值和getBoundingClientRect方法都会导致回流
     * 滚动事件会绑定多个事件处理函数，阻塞UI渲染
     */
    scroll() {
      const dom = document.querySelector('.box');
      const clientHeight = document.documentElement.clientHeight;
      window.addEventListener('scroll', () => {
        const top = dom.getBoundingClientRect().top;
        if (top < clientHeight) {
          console.log('可见');
        }
      });
    },
    dd() {
      const box = document.querySelector('.box');
      const intersectionObserver = new IntersectionObserver(entries => {
        entries.forEach(item => {
          if (item.isIntersecting) {
            console.log('进入可视区域', item);
          }
        });
      });
      intersectionObserver.observe(box);
    }
  }
};
</script>

<style lang="scss" scoped>
.test {
  height: 100vh;
}
.box {
  height: 400px;
}
</style>
